﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO.Ports;
using System.IO;

namespace VoltageLogger
{
    class Program
    {
        const int       MAXVOLTS= 40;
        const double    ANALOG_RESOL = MAXVOLTS / 1024.0;
        const string    LOGMASK = "{0:dd/MM/yyyy HH:mm} : {1:##0.0000} volts";

        static void Main (string [] args)
        {
            string  portName= args[0];
            int     bdRate  = int.Parse(args[1]);

            SerialPort sp = new SerialPort(portName, bdRate);
            Console.WriteLine(
                "Puerto={0} BaudRate={1}", 
                portName, bdRate
            );

            sp.Open();
            Console.WriteLine("Ok");
            
            int _ultimoMinuto = DateTime.Now.Minute;

            for (; ; )
            {
                Thread.Sleep(15);
                if (_ultimoMinuto != DateTime.Now.Minute)
                {
                    _ultimoMinuto = DateTime.Now.Minute;
                    double voltaje = pedirVoltaje(sp);
                    
                    string log = string.Format(
                        LOGMASK, 
                        DateTime.Now, 
                        voltaje
                    );
                    loguear(log);
                    Console.WriteLine (log);
                }
            }
        }

        static double pedirVoltaje(SerialPort sp)
        {
            sp.ReadExisting();
            sp.Write("x");
            
            int analogRead = 0;

            for (; ; )
            {
                int byteLeido = sp.ReadByte();

                if (byteLeido == '\n')
                    break;
                else if ((byteLeido >= '0') && (byteLeido <= '9'))
                    analogRead =
                        (analogRead * 10) +
                        (byteLeido - '0');
            }

            Console.WriteLine("analog = {0}", analogRead);

            return ((double)analogRead) * ANALOG_RESOL;
        }

        static void loguear(string log)
        {
            using (StreamWriter sw = File.AppendText("volts.txt"))
            {
                sw.WriteLine(log);
                sw.Close();
            }
        }

        
        
        
    }
}
